package com.hobbit.analyze.analyzers
{
	import com.hobbit.analyze.base.LoadItem;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	import starling.textures.Texture;
	import starling.textures.TextureAtlas;
	
	/**
	 * sheet解析器 
	 * @author 晓晔
	 * 
	 */
	public class SheetAnalyze implements IAnalyze
	{
		public function SheetAnalyze()
		{
		}
		
		private var _byteArray:ByteArray;
		
		public function getDataList():Dictionary
		{
			return _sheetList;
		}
		
		private var _sheetList:Dictionary = new Dictionary();
		private var _compFnList:Dictionary = new Dictionary();
		private var _loadItemList:Dictionary = new Dictionary();
		private var _xmlList:Dictionary = new Dictionary();
		public function analyze(byteArray:ByteArray, loadItem:LoadItem, compFn:Function):void
		{
			
			var loader:Loader = new Loader();
			byteArray.uncompress();
			byteArray.position = 0;
			
			var xml:XML = XML(byteArray.readUTF());
			
			_compFnList[loader] = compFn;
			_xmlList[loader] = xml;
			_loadItemList[loader] = loadItem;
			
			var imgBytes:ByteArray = new ByteArray();
			byteArray.readBytes(imgBytes);
			
			loader.loadBytes(imgBytes);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoaderComplete);
		}
		
		protected function onLoaderComplete(event:Event):void
		{
			var targetLoader:Loader = event.target.loader;
			var tempImg:Bitmap = event.target.content as Bitmap;
			event.target.removeEventListener(Event.COMPLETE,onLoaderComplete);
			
			var texture:Texture = Texture.fromBitmap(tempImg);
			var sTextureAtlas:TextureAtlas = new TextureAtlas(texture, _xmlList[targetLoader]);
			
			var loadItem:LoadItem = _loadItemList[targetLoader];
			loadItem.result = sTextureAtlas;
			
			_sheetList[loadItem.name] = sTextureAtlas;
			var compFn:Function = _compFnList[targetLoader];
			if(compFn!=null)
			{
				compFn(loadItem);
			}
			
			delete _xmlList[targetLoader];
			delete _loadItemList[targetLoader];
			delete _compFnList[targetLoader];
			
			_byteArray = null;
			targetLoader = null;
			
		}
		
		/**
		 * 返回texture 
		 * @param key
		 * @param subKey
		 * @return 
		 * 
		 */
		public function getData(key:String, subKey:String):*
		{
			var retObj:Object = _sheetList[key];
			if(retObj == null)
			{
				retObj = _sheetList[key + "$" + subKey];
			}
			return retObj;
		}
		
	}
}